package com.hb.trans.mvp.ui.fragment


import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.net.Uri
import androidx.appcompat.app.AlertDialog
import com.alibaba.android.arouter.launcher.ARouter
import com.basiclib.base.BaseFragment
import com.basiclib.utils.GoToScoreUtils
import com.basiclib.utils.L
import com.basiclib.utils.versionCode
import com.basiclib.utils.versionName
import com.hb.trans.R
import com.hb.trans.bean.Update
import com.hb.trans.bean.VersionInfo
import com.hb.trans.global.ACTIVITY_HOME_ABOUT_US
import com.hb.trans.global.ACTIVITY_HOME_FEEDBACK
import com.hb.trans.mvp.contract.UserCenterContract
import com.hb.trans.mvp.presenter.UserCenterPresenter
import com.hb.trans.utils.VersionUpdataHelper
import com.jakewharton.rxbinding2.view.clicks
import dagger.android.support.AndroidSupportInjection
import kotlinx.android.synthetic.main.fragment_user_center.*
import javax.inject.Inject


class UserCenterFragment : BaseFragment<UserCenterPresenter>(), UserCenterContract.View {
    override fun setViewId(): Int {
       return R.layout.fragment_user_center
    }

    override fun doOnInvisible() {
    }

    override fun doOnVisible() {
    }

    override fun setGetById(data: Update?) {
        val mVcode = mContext.packageManager.getPackageInfo(mContext.packageName, 0).versionCode
        val upVCode = data?.app_version!!.toInt()
        if (mVcode < upVCode) {
            VersionUpdataHelper(activity, data?.android_url, true)
        }
    }


    @Inject
    lateinit var mPresenter: UserCenterPresenter

//    lateinit var rootView: View

    companion object {
        fun newInstance(): UserCenterFragment {
            val fragment = UserCenterFragment()
            return fragment
        }
    }

//    override fun initView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
//        rootView = inflater.inflate(R.layout.fragment_user_center, container, false)
//        return rootView
//    }

    override fun onFragmentInject() {
        AndroidSupportInjection.inject(this)
    }

    override fun attachView() {
        mPresenter.attachView(this)
    }

    override fun initView() {
        tvVersion.text = "V${mContext.versionName()}"
    }

    override fun initData() {
    }

    @SuppressLint("CheckResult")
    override fun setListener() {
        tvSugestion.clicks().subscribe {
            ARouter.getInstance().build(ACTIVITY_HOME_FEEDBACK).navigation()
        }

        tvAboutUs.clicks().subscribe {
            ARouter.getInstance().build(ACTIVITY_HOME_ABOUT_US).navigation()
        }
        llVersion.clicks().subscribe {
            //            mPresenter.getVersionInfo()
            mPresenter.getById()
        }
    }

    override fun updateInfo(version: VersionInfo?) {
        version?.let {
            L.d(msg = "${mContext.versionCode()}")
            if (it.version_android.toInt() <= mContext.versionCode()) {
                showShortToast("已是最新版本")
            } else {
                AlertDialog.Builder(mContext)
                    .setTitle("更新提示")
                    .setMessage("已有最新版本发布，是否更新")
                    .setCancelable(false)
                    .setPositiveButton("更新") { _, _ ->
                        if (isMobile_spExist()) {
                            goToMarket(mContext, mContext.packageName)
                        } else {
                            GoToScoreUtils.goToMarket(mContext, mContext.packageName)
                        }
                    }
                    .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                    .show()
            }
        }
    }

    private fun isMobile_spExist(): Boolean {
        val manager = mContext.packageManager
        val pkgList: MutableList<PackageInfo> = manager.getInstalledPackages(0);
        for (i in 0 until pkgList.size) {
            val pI = pkgList[i]
            if (pI.packageName.equals("com.tencent.android.qqdownloader", false))
                return true
        }
        return false
    }

    fun goToMarket(context: Context, packageName: String) {
        val uri = Uri.parse("market://details?id=$packageName")
        val goToMarket = Intent(Intent.ACTION_VIEW, uri)
        try {
            goToMarket.setClassName("com.tencent.android.qqdownloader", "com.tencent.pangu.link.LinkProxyActivity")
            context.startActivity(goToMarket)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            GoToScoreUtils.goToMarket(mContext, mContext.packageName)
        }

    }
}
